package org.bonorsoft.modules.MobileDingding.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.system.util.JwtUtil;
import org.bonorsoft.common.system.vo.LoginDingUser;
import org.bonorsoft.common.util.RedisUtil;
import org.bonorsoft.common.util.TokenUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.service.ISysDingUserService;
import org.bonorsoft.modules.dingding.util.SendNoticeUtil;
import org.bonorsoft.modules.education.entity.Addressee;
import org.bonorsoft.modules.education.entity.Notice;
import org.bonorsoft.modules.education.service.IAddresseeService;
import org.bonorsoft.modules.education.service.IEnclosureService;
import org.bonorsoft.modules.education.service.INoticeService;
import org.bonorsoft.modules.education.service.IResponseService;
import org.bonorsoft.modules.education.vo.FileVo;
import org.bonorsoft.modules.education.vo.NoticeVo;
import org.bonorsoft.modules.education.vo.ResponseVo;
import org.bonorsoft.modules.education.vo.SendVo;
import org.bonorsoft.modules.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/mobile")
public class MobileNoticeController extends BonorController<Notice, INoticeService> {
    private String prefix = "mobile/mobileEdu/office/notice";

    @Autowired
    private IAddresseeService addresseeService;

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IEnclosureService enclosureService;

    @Autowired
    private IResponseService responseService;

    @Autowired
    private ISysDingUserService dingUserService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 通知管理
     */
    @GetMapping("/notice")
    public String mobileOfficeCenter(ModelMap mmap, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        mmap.put("token", token);
        //        SysMenu menus = menuService.selectMenuById(1152L);
        //        mmap.put("menu",menus);
        return prefix + "/notice";
    }

    /**
     * 发通知界面
     */
    @GetMapping("/notice/add")
    public String add(ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        FileVo file = new FileVo();
        map.put("notice", new Notice());
        map.put("addresseeName", "");
        map.put("file", file);
        map.put("realNames", "");
        return prefix + "/add";
    }

    @AutoLog(value = "发通知")
    @PostMapping(value = "/notice/add")
    @ResponseBody
    public Result<?> add(@Validated Notice notice, String addresseeName, String file) {
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");//uuid
        notice.setNoticeSender(user.getUserid()).setNoticeId(uuid).setNoticeSendingTime(new Date()).setNoticeStatus("1");//设置发件人、id、发送时间

        if (!addresseeName.isEmpty()) {
            String noticeMessage = notice.getNoticeMessage();//是否发送短信
            boolean message = noticeMessage.equals("1");//是否发送短信1发送0不发送
            boolean messageStatus = true;//短信发送状态成功&失败
            String noticeMessageStatus;//短信发送状态1成功0失败
            String[] addresseeNames = addresseeName.split(",");
            //收件人数组去重=>收件人list
            List<String> addresseeNameList = new ArrayList<>();
            for (int i = 0; i < addresseeNames.length; i++) {
                if (!addresseeNameList.contains(addresseeNames[i])) {
                    addresseeNameList.add(addresseeNames[i]);
                }
            }

            int SendCount = 0;
            for (String addressee : addresseeNameList) {
                addresseeService.add(uuid, addressee);
                String addresseeId = addresseeService.getByName(uuid, addressee).getAddresseeId();
                String userId = dingUserService.getUserByMobile(addressee).getUserid();
                String token = JwtUtil.sign(userId, addressee);
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
                /*对接钉钉通知接口*/
                try {
                    SendNoticeUtil.SendDingNotice(userId, addresseeId, token);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                /*是否发送短信*/
                if (message) {
                    /*对接短信接口发送*/
                    String tpl_value = URLEncoder.encode("#name#=" + user.getName() + "&#noticeTitle#=" + notice.getNoticeTheme());
                    int i = SendNoticeUtil.SendMessage(addressee, tpl_value);
                    SendCount += i;
                }
            }

            if (SendCount < addresseeNameList.size()) {
                messageStatus = false;
            }

            //发送成功时messageStatus为true失败时为false
            if (messageStatus) {
                noticeMessageStatus = "1";
            }
            else {
                noticeMessageStatus = "0";
            }
            notice.setNoticeMessageStatus(noticeMessageStatus);
        }
        else {//没有收件人，就设置为草稿
            notice.setNoticeStatus("0");
        }

        //附件
        if (oConvertUtils.isNotEmpty(file)) {
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            enclosureService.add(uuid, fileName, file);
        }

        noticeService.save(notice);
        return Result.ok("发送成功！");
    }

    /**
     * 选择收件人树
     */
    @GetMapping("/notice/tree")
    public String checkTree(ModelMap mmap, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        mmap.put("token", token);
        return prefix + "/tree";
    }

    /**
     * 收件箱
     */
    @GetMapping("/notice/receive")
    public String receivedList(ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        List<NoticeVo> notices = addresseeService.mobileList(user.getMobile());
        map.put("notices",notices);
        return prefix + "/receive";
    }

    /**
     * 收件箱查询
     */
    /////////
    @GetMapping("/notice/toSearch")
    public String toSearch(ModelMap map, HttpServletRequest request, NoticeVo notice, String keyWord, String startTime, String endTime){
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        QueryWrapper<NoticeVo> queryWrapper = QueryGenerator.initQueryWrapper(notice, request.getParameterMap());
        List<NoticeVo> notices = addresseeService.searchList(queryWrapper, keyWord, startTime, endTime);
        map.put("notices",notices);
        return prefix + "/receive";
    }

    /**
     * 收件箱详细信息页面
     */
    @GetMapping("/notice/receivedDetail/{id}")
    public String receivedDetail(@PathVariable("id") String id, ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        Addressee addressee = addresseeService.getById(id);
        Notice notice = noticeService.getByAddresseeId(id);
        if(addressee.getAddresseeRead().equals("0")){
            addressee.setAddresseeRead("1").setReadTime(new Date());
            addresseeService.updateById(addressee);
        }
        FileVo fileVo = new FileVo();
        if (enclosureService.countByNoticeId(notice.getNoticeId()) > 0) {
            String file = enclosureService.getFileByNoticeId(notice.getNoticeId());
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            fileVo.setFileName(fileName);
            fileVo.setFileRoute(file);
        }
        map.put("file", fileVo);
        map.put("addressee", addressee);
        map.put("notice", notice);
        map.put("response", responseService.getResponseByNoticeIdAndName(notice.getNoticeId(), addressee.getAddresseeName()));
        return prefix + "/receivedDetail";
    }

    /**
     * 收件箱通过id删除
     */
    @AutoLog(value = "收件箱删除")
    @PostMapping(value = "/notice/deleteAddressee")
    @ResponseBody
    public Result<?> deleteAddressee(@RequestParam(name = "id", required = true) String id) {
        addresseeService.removeById(id);
        return Result.ok("删除成功!");
    }

    @AutoLog(value = "会议报名")
    @PostMapping(value = "/notice/signUp")
    @ResponseBody
    public Result<?> signUpModify(@Validated Addressee addressee) {
        if (oConvertUtils.isNotEmpty(addressee.getParticipantsName())) {
            addressee.setSignUp("1");
            addresseeService.updateById(addressee);
            return Result.ok("报名成功");
        } else {
            addressee.setSignUp("0");
            addresseeService.updateById(addressee);
            return Result.ok("取消报名成功");
        }
    }

    /**
     * 转发
     */
    @GetMapping("/notice/toForward/{id}")
    public String toForward(@PathVariable("id") String id, ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        Notice notice = noticeService.getById(id);
        notice.setNoticeContent("——————转发信息—————— \n从：" + dingUserService.getById(notice.getNoticeSender()).getName() + "\n内容:" + notice.getNoticeContent());
        map.put("notice", notice);
        FileVo fileVo = new FileVo();
        if (enclosureService.countByNoticeId(notice.getNoticeId()) > 0) {
            String file = enclosureService.getFileByNoticeId(id);
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            fileVo.setFileName(fileName);
            fileVo.setFileRoute(file);
        }
        map.put("file", fileVo);
        map.put("addresseeName", "");
        return prefix+"/add";
    }

    /**
     * 确认回复
     */
    @AutoLog(value = "回复")
    @PostMapping(value = "/notice/addResponse")
    @ResponseBody
    public Result<?> addResponse(@Validated ResponseVo response) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        response.setResponseId(uuid).setResponseSender(user.getMobile()).setResponseTime(new Date());
        String file = response.getFileRoute();
        responseService.save(response);
        if (oConvertUtils.isNotEmpty(file)) {
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            enclosureService.add(uuid, fileName, file);
        }//附件
        return Result.ok("回复成功！");
    }

    /**
     * 发件箱
     */
    @GetMapping("/notice/sendList")
    public String sendList(ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        List<SendVo> notices = noticeService.mobileSendList(user.getUserid());
        map.put("notices",notices);
        return prefix + "/sendList";
    }

    /**
     * 发件箱详细信息页面
     */
    @GetMapping("/notice/sendDetail/{id}")
    public String sendDetail(@PathVariable("id") String id, ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);

        Notice notice = noticeService.getById(id);
        map.put("notice", notice);

        FileVo fileVo = new FileVo();
        if (enclosureService.countByNoticeId(id) > 0) {
            String file = enclosureService.getFileByNoticeId(id);
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            fileVo.setFileName(fileName);
            fileVo.setFileRoute(file);
        }
        map.put("file", fileVo);

        List<Addressee> yseAddressees = addresseeService.getYesByNotice(id);//已读收件人列表
        List<Addressee> noAddressees = addresseeService.getNoByNotice(id);//未读收件人列表
        List<Addressee> signAddressees = addresseeService.getSignByNoticeId(id);//报名会议人员列表
        map.put("yseAddressees", yseAddressees);
        map.put("noAddressees", noAddressees);
        map.put("signAddressees", signAddressees);

        List<ResponseVo> responseByNoticeId = responseService.getResponseByNoticeId(id);
        map.put("response", responseByNoticeId);

        return prefix + "/sendDetail";
    }

    /**
     * 重发
     */
    @AutoLog(value = "通知-重发")
    @PostMapping(value = "/notice/sendAgain")
    @ResponseBody
    public Result<?> sendAgain(@RequestParam(name = "id") String id) {
        Notice notice = noticeService.getById(id);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");//uuid
        notice.setNoticeId(uuid).setNoticeSendingTime(new Date());
        List<Addressee> addressees = addresseeService.getByNoticeId(id);
        for (Addressee addressee : addressees) {
            addresseeService.add(uuid, addressee.getAddresseeName());
        }
        //附件复制路径uuid赋值
        if (enclosureService.countByNoticeId(id) > 0) {
            String file = enclosureService.getFileByNoticeId(id);
            String[] split = file.split("/");
            String filestr = split[split.length - 1];
            String fileName = filestr.substring(0, filestr.lastIndexOf("_"))+filestr.substring(filestr.indexOf("."));
            enclosureService.add(uuid, fileName, file);
        }
        noticeService.save(notice);
        return Result.ok("重发成功！");
    }

    /**
     * 撤回（到草稿箱）
     */
    @AutoLog(value = "通知-撤回")
    @PostMapping(value = "/notice/toReturn")
    @ResponseBody
    public Result<?> toReturn(@RequestParam(name = "id") String id) {
        Notice notice = noticeService.getById(id);
        addresseeService.removeByNoticeId(id);
        responseService.removeByNoticeId(id);
        if (addresseeService.getByNoticeId(id).size() == 0) {
            notice.setNoticeSendingTime(new Date()).setNoticeStatus("0");
            noticeService.updateById(notice);
        }
        return Result.ok("撤回成功！");
    }

    /**
     * 草稿箱
     */
    @GetMapping("/notice/draftList")
    public String draftList(ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        List<NoticeVo> notices = noticeService.mobileDraftList(user.getUserid());
        map.put("notices",notices);
        return prefix + "/draftList";
    }

    /**
     * 删除（放入废件箱）
     */
    @AutoLog(value = "通知-删除")
    @PostMapping(value = "/notice/toDelete")
    @ResponseBody
    public Result<?> toDelete(@RequestParam(name = "id") String id) {
        Notice notice = noticeService.getById(id);
        notice.setNoticeSendingTime(new Date()).setDelFlag("1");
        noticeService.updateById(notice);
        return Result.ok("删除成功！");
    }

    /**
     * 草稿箱发送
     */
    @GetMapping("/notice/sendCheck/{id}")
    public String sendCheck(@PathVariable("id") String id, ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        Notice notice = noticeService.getById(id);
        map.put("notice", notice);
        FileVo fileVo = new FileVo();
        if (enclosureService.countByNoticeId(notice.getNoticeId()) > 0) {
            String file = enclosureService.getFileByNoticeId(notice.getNoticeId());
            String[] split = file.split("/");
            fileVo.setFileName(split[split.length - 1]);
            fileVo.setFileRoute(file);
        }
        map.put("file", fileVo);
        map.put("addresseeName", "");
        return prefix + "/add";
    }


    /**
     * 废件箱
     */
    @GetMapping("/notice/deleteList")
    public String deleteList(ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();//取得当前用户
        List<NoticeVo> notices = noticeService.mobileDeleteList(user.getUserid());
        map.put("notices",notices);
        return prefix + "/deleteList";
    }

    /**
     * 草稿/废件箱详细信息页面
     */
    @GetMapping("/notice/detail/{id}")
    public String detail(@PathVariable("id") String id, ModelMap map, HttpServletRequest request) {
        String token = TokenUtils.getTokenByRequest(request);
        map.put("token", token);
        Notice notice = noticeService.getById(id);
        map.put("notice", notice);
        FileVo fileVo = new FileVo();
        if (enclosureService.countByNoticeId(notice.getNoticeId()) > 0) {
            String file = enclosureService.getFileByNoticeId(notice.getNoticeId());
            String[] split = file.split("/");
            fileVo.setFileName(split[split.length - 1]);
            fileVo.setFileRoute(file);
        }
        map.put("file", fileVo);
        return prefix + "/detail";
    }

    /**
     * 废件箱还原
     */
    @AutoLog(value = "废件箱-还原")
    @PostMapping(value = "/toRecovery")
    @ResponseBody
    public Result<?> toRecovery(@RequestParam(name = "id") String id) {
        Notice notice = noticeService.getById(id);
        notice.setDelFlag("0");
        noticeService.updateById(notice);
        return Result.ok("还原成功！");
    }


    /**
     * 废件箱通过id删除
     */
    @AutoLog(value = "废件箱彻底删除")
    @DeleteMapping(value = "/notice/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        enclosureService.deleteByNoticeId(id);
        noticeService.removeById(id);
        return Result.ok("删除成功!");
    }




}
